home *** CD-ROM | disk | FTP | other *** search
- /* CPROG17.CPP - Random access to plant pests held in a file */
-
- #include <stdio.h>
- #include <conio.h>
- #include <dos.h>
- #include <stdlib.h>
-
- #define RECLEN 16
- #define NUMRECS 10
-
- /* Load file 10recs.dat to see the structure - 10 records
- padded to 16 characters each. */
-
- void main(void)
- {
- FILE *fp; // The file pointer
- int c; // Holds a code that controls the main loop
- char kbstring[5], record[RECLEN+1];
-
- /* kbstring[] holds the user input: up to 2 digits + '\0' + 1 byte to specify
- the maximum length of the input string + 1 byte to report how many were
- actually entered=5 bytes total. See Help on cgets().
- record[] holds a record read from disk - 16 chars + '\0' */
-
-
- if( ! (fp=fopen("10recs.dat", "r")) ) // Open the data file
- {
- cputs("Can't find data file 10RECS.DAT\n");
- exit(0);
- }
-
- record[RECLEN]='\0'; // Intialise last element in record[] with '\0'
- c=0; // In case garbage value in c happens to be
- // ASCII for Q causing premature termination
- while( c != 'Q' )
- {
- clrscr();
- printf("Enter a number from 1 to %d and press [Return]\n", NUMRECS);
- printf("to see an exciting new plant pest!\n");
- printf("Enter [Q][Return] to quit\n");
-
- kbstring[0]=3; // Allow input of up to 2 chars + '\0'= 3 max
- cgets(kbstring); // Read Help on cgets() for justification of
- // previous line.
-
- if( kbstring[1] == 0 ) // Filter out invalid input values - like no input. '\0' doesn't count in number of chars read.
- {
- c=0; // Make sure c is a non-'Q' value
- continue; // Skip rest of loop and go to while() line
- }
- if( kbstring[1]==1 && (kbstring[2]=='Q' || kbstring[2]=='q') )
- { // Does the user want to quit?
- c='Q';
- continue;
- }
- c=atoi(&kbstring[2]); // Attempt to convert input (which starts at element [2] to an integer. See atoi() in Help.
- if( c<1 || c>NUMRECS )
- {
- c=0;
- continue;
- }
-
- // c must now contain a valid value 1-NUMRECS.
-
- fseek(fp, RECLEN*(c-1), SEEK_SET);
- /* Fseek moves the position in the file from which the
- next data will be read. SEEK_SET is a macro which says
- that the distance specified in parameter 2 is from the
- start of the file. Ctrl+Shift+F1 on it to see other
- possibilities. The first byte in the file is at
- offset zero, so record X is at offset RECLEN*X. Since
- c's minimum value is 1, it must be reduced by 1 in the
- calculation */
-
- fread(record, RECLEN, 1, fp);
- /* Another of the many ways to read data from a file.
- fread()'s first parameter is a pointer to a place
- where the read-in data can be placed.
- The second parameter is the size (in bytes) of the
- daat item to be read. Here it is 10 bytes.
- The third parameter is the number of items to read.
- So we're reading 1 object, 10 bytes long, into
- record[]. 10 objects 1 byte long would have the
- same effect. */
-
- printf("\nPest %d is %s\n", c, record);
- delay(2000);
- }
-
- fclose(fp);
-
- }
-
-
-
-
-